package com.lanmei.group.weixin.controller.admin;

import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresRoles;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.lanmei.group.weixin.interceptor.ManagerInterceptor;
import com.lanmei.group.weixin.model.ManagerInfo;
import com.lanmei.group.weixin.model.RoleInfo;
import com.lanmei.group.weixin.model.UserRoleRef;
import com.lanmei.group.weixin.utils.ShiroUtil;
@Clear(ManagerInterceptor.class)
@RequiresRoles(value = {"admin" })
public class RoleInfoController extends Controller {
	
	public void list(){
		Page<RoleInfo> page = new RoleInfo().paginate(1, 10, "select *", "from role_info order by create_time desc");
		setAttr("page", page);
		render("list.jsp");
	}
	public void toAdd(){
		render("add.jsp");
	}
	public void add(){
		RoleInfo role = getModel(RoleInfo.class, "role");
		role.setCreateTime(new Date());
		role.setCreateUser(ShiroUtil.getLoginName());
		role.save();
		this.redirect("/admin/roleinfo/list");
	}
	public void toEdit(){
		int roleId = getParaToInt("roleId");
		RoleInfo role = new RoleInfo().dao.findById(roleId);
		setAttr("role", role);
		render("edit.jsp");
	}
	public void update(){
		RoleInfo role = getModel(RoleInfo.class, "role");
		role.setUpdateTime(new Date());
		role.setUpdateUser(ShiroUtil.getLoginName());
		role.update();
		this.redirect("/admin/roleinfo/list");
	}
	public void delete(){
		int roleId = getParaToInt("roleId");
		RoleInfo role = new RoleInfo().dao.findById(roleId);
		role.delete();
		this.redirect("/admin/roleinfo/list");
	}
	public void toManagerRole(){
		String loginName = getPara("loginName");
		ManagerInfo manager = new ManagerInfo().findManagerInfoByLoginName(loginName);
		if(null!=manager){
			setAttr("manager", manager);
			List<RoleInfo> list = new RoleInfo().dao.find("select * from role_info where role_name != 'admin'");
			setAttr("roles", list);
			List<RoleInfo> hasRoles = new RoleInfo().dao.find("select r.* from role_info r ,manager_info m ,user_role_ref f where r.`role_id` = f.`role_id` and f.`manager_id`= m.`manager_id` and m.`manager_id` = "+manager.getManagerId());
			setAttr("hasRoles", hasRoles);
		}
		render("manager_role.jsp");
	}
	public void managerRole(){
		int managerId = getParaToInt("managerId");
		Integer [] roleIds = getParaValuesToInt("roleIds");
		if(null==roleIds){
			this.redirect("/admin/roleinfo/toManagerRole");
			return;
		}
		for (int i = 0; i < roleIds.length; i++) {
			UserRoleRef ref =null;
			ref = new UserRoleRef().findUserRoleRefs(managerId, roleIds[i]);
			if(ref!=null){
				continue;
			}
			ref = new UserRoleRef();
			ref.setManagerId(managerId);
			ref.setRoleId(roleIds[i]);
			ref.save();
		}
		this.redirect("/admin/roleinfo/toManagerRole");
	}

}
